<template>
  <div class="category-page">
    <a-page-header
      title="食物分类管理"
      sub-title="添加、编辑和删除食物分类"
      @back="() => $router.push('/diet')"
    >
      <template #extra>
        <a-button type="primary" @click="showAddModal">
          添加分类
        </a-button>
      </template>
    </a-page-header>

    <a-card :bordered="false" style="margin-top: 16px">
      <a-table
        :columns="columns"
        :data-source="categories"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'icon'">
            <img
              v-if="record.icon"
              :src="record.icon"
              :alt="record.name"
              style="width: 40px; height: 40px; object-fit: cover;"
            />
            <span v-else>无图标</span>
          </template>
          
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个分类吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteCategory(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑分类的模态框 -->
    <a-modal
      :visible="modalVisible"
      :title="formMode === 'add' ? '添加分类' : '编辑分类'"
      @cancel="modalVisible = false"
      @ok="handleSubmit"
      :confirmLoading="submitLoading"
    >
      <a-form
        :model="categoryForm"
        :rules="rules"
        ref="categoryFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="name" label="分类名称">
          <a-input v-model:value="categoryForm.name" />
        </a-form-item>
        
        <a-form-item name="icon" label="图标URL">
          <a-input v-model:value="categoryForm.icon" placeholder="输入图标URL" />
        </a-form-item>
        
        <a-form-item name="sortOrder" label="排序">
          <a-input-number v-model:value="categoryForm.sortOrder" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="status" label="状态">
          <a-switch v-model:checked="categoryForm.status" :checked-value="1" :un-checked-value="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';

export default defineComponent({
  setup() {
    const loading = ref(false);
    const submitLoading = ref(false);
    const modalVisible = ref(false);
    const formMode = ref('add'); // 'add' 或 'edit'
    const categoryFormRef = ref(null);
    
    // 分类数据
    const categories = ref([]);
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    });
    
    // 分类表单
    const categoryForm = reactive({
      id: null,
      name: '',
      icon: '',
      sortOrder: 0,
      status: 1
    });
    
    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入分类名称' }]
    };
    
    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
      },
      {
        title: '图标',
        dataIndex: 'icon',
        key: 'icon'
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '排序',
        dataIndex: 'sortOrder',
        key: 'sortOrder'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status'
      },
      {
        title: '操作',
        key: 'action'
      }
    ];
    
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        loading.value = true;
        const response = await axios.get('/admin/diet/categories');
        if (response.data.code === 0) {
          categories.value = response.data.data || [];
          pagination.total = categories.value.length;
        } else {
          message.error(response.data.msg || '获取分类列表失败');
        }
      } catch (error) {
        console.error('获取分类列表失败', error);
        message.error('获取分类列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 表格变化处理(分页、排序等)
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
    };
    
    // 显示添加模态框
    const showAddModal = () => {
      formMode.value = 'add';
      // 重置表单
      Object.keys(categoryForm).forEach(key => {
        if (key === 'status') {
          categoryForm[key] = 1;
        } else if (key === 'sortOrder') {
          categoryForm[key] = 0;
        } else if (key === 'id') {
          categoryForm[key] = null;
        } else {
          categoryForm[key] = '';
        }
      });
      modalVisible.value = true;
    };
    
    // 显示编辑模态框
    const showEditModal = (record) => {
      formMode.value = 'edit';
      // 填充表单
      Object.keys(categoryForm).forEach(key => {
        if (record[key] !== undefined) {
          categoryForm[key] = record[key];
        }
      });
      modalVisible.value = true;
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await categoryFormRef.value.validate();
        submitLoading.value = true;
        
        let response;
        if (formMode.value === 'add') {
          response = await axios.post('/admin/diet/categories', categoryForm);
        } else {
          response = await axios.put(`/admin/diet/categories/${categoryForm.id}`, categoryForm);
        }
        
        if (response.data.code === 0) {
          message.success(formMode.value === 'add' ? '添加成功' : '更新成功');
          modalVisible.value = false;
          fetchCategories();
        } else {
          message.error(response.data.msg || (formMode.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error(formMode.value === 'add' ? '添加失败' : '更新失败', error);
        message.error(formMode.value === 'add' ? '添加失败' : '更新失败');
      } finally {
        submitLoading.value = false;
      }
    };
    
    // 删除分类
    const deleteCategory = async (id) => {
      try {
        loading.value = true;
        const response = await axios.delete(`/admin/diet/categories/${id}`);
        if (response.data.code === 0) {
          message.success('删除成功');
          fetchCategories();
        } else {
          message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败');
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchCategories();
    });
    
    return {
      loading,
      submitLoading,
      modalVisible,
      formMode,
      categoryFormRef,
      categories,
      pagination,
      categoryForm,
      rules,
      columns,
      handleTableChange,
      showAddModal,
      showEditModal,
      handleSubmit,
      deleteCategory
    };
  }
});
</script>

<style scoped>
.category-page {
  margin: 0 16px;
}
</style> 